package com.swadar.dao;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.swadar.beans.dataobject.UserDO;
import com.swadar.beans.dataobject.UserLoginDo;
import com.swadar.beans.valueobject.UserVO;


@Component
public class UserDAO {

	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	private String USER = "INSERT INTO USERS(NAME,E_MAIL,GENDER) VALUES(?,?,?)";
	private String USER_LOGIN = "INSERT INTO USER_LOGIN(USER_ID,USER_NAME,E_MAIL,PASSWORD) VALUES(?,?,?,?)";
	private String GET_USER = "SELECT * FROM USER_LOGIN";
	private String USER_LIST = "SELECT * FROM USERS";
	
	public void addUser(UserDO userDO){
		Object[] params = { userDO.getName(),userDO.geteMail(),userDO.getGender() };
		jdbcTemplate.update(USER,params);
	}
	
	public Long getUserId(){
		UserDO userDO = new UserDO();
		Long userId = null;
		BeanPropertyRowMapper<UserDO> rowMapper = new BeanPropertyRowMapper<UserDO>(UserDO.class);
		List<UserDO> list = jdbcTemplate.query(USER_LIST, rowMapper);
		int length = list.size()-1;
			userDO = list.get(length);
			userId = userDO.getId();
		return userId;
		
	}
	
	public void addUserLogin(UserLoginDo userLoginDo){
		Object[] params = { userLoginDo.getUserId(),userLoginDo.getUserName(),userLoginDo.geteMail(),userLoginDo.getPassword() };
		jdbcTemplate.update(USER_LOGIN,params);
	}
	
	public boolean Validation(UserVO userVO){
		boolean valid = false;
		BeanPropertyRowMapper<UserLoginDo> rowMapper = new BeanPropertyRowMapper<UserLoginDo>(UserLoginDo.class);
		List<UserLoginDo> userList = jdbcTemplate.query(GET_USER, rowMapper); 
		for(int i = 0; i<userList.size(); i++){
			UserLoginDo userLoginDo = new UserLoginDo();
			if(userVO.geteMail().equalsIgnoreCase(userLoginDo.geteMail())){
				if(userVO.getPassword().equalsIgnoreCase(userLoginDo.getPassword())){
					valid = true;
				}
			}
		}
		return valid;
	}
	
}
